The ECMAScript specification allows for creating block-level lexical declarations (let
, const
, function
, and
class
) in any block statement or expression. However, when these declarations are made inside the case
or
default
clause of a switch
statement, they are not confined to the block of that case
or default
clause. Instead, they apply to the whole switch
block but only get initialized when the cases are reached, which can lead to unexpected
behavior.
switch (foo) {
case 1:
let x = 1; // Noncompliant
break;
case 2:
const y = 2; // Noncompliant
break;
case 3:
function f() {} // Noncompliant
break;
case 4:
class C {} // Noncompliant
break;
}
To fix this, you can create a nested block within each case
or default
clause, ensuring each declaration is properly
scoped to its respective block.
switch (foo) {
case 1: {
let x = 1;
break;
}
case 2: {
const y = 2;
break;
}
case 3: {
function f() {}
break;
}
case 4: {
class C {}
break;
}
}